<%@ include file="/WEB-INF/views/taglib.jsp" %>
<h3>Delivery Order Form</h3>	
	<form:form id="form" method="post" modelAttribute="deliveryOrder"  cssClass="simpleForm deliveryOrderForm" >
		<form:hidden path="deliveryOrderId" />
		<div class="action">
	  	<c:choose>
	  		<c:when test="${deliveryOrder.deliveryOrderId==null}">
	  			<button type="button" class="button positive" onclick="formSubmit()">
	  			Confirm
	  			</button>
	  			<a href="<c:url value="/deliveryOrder/create" />" class="button positive">Cancel</a>
	  			<button type="button" class="button positive" onclick="location.href='<c:url value="/deliveryOrder/search" />'">Back</button>
	  		</c:when>
	  		<c:when test="${deliveryOrder.deliveryOrderId!=null}">
	  			<a href="<c:url value="/deliveryOrder/print/${deliveryOrder.deliveryOrderId}" />" target="_blank" class="button">Print</a>
  				<button type="button" class="button positive" onclick="location.href='<c:url value="/deliveryOrder/search" />'">Back</button>
	  		</c:when>
	  	</c:choose>
	 	</div>	
		<div class="clear" style="height:1px">&nbsp;</div>
		<jsp:include page="/WEB-INF/views/message.jsp"></jsp:include>
	  	<fieldset>
	  		<legend>Delivery Order Info</legend>
	  		<div class="span-11">
				  		<aims:column cssErrorClass="error" path="deliveryOrderCode" >
				  		<form:label path="deliveryOrderCode">
				  			DO No
				 		</form:label>
				  		<form:input path="deliveryOrderCode" id="deliveryOrderCode"/> 
				  		<form:errors path="deliveryOrderCode"  cssClass="errorSimple" /> 
						</aims:column>
			
			
						<c:choose>
				  			<c:when test="${deliveryOrder.deliveryOrderId==null}">
						<aims:column cssErrorClass="error" path="purchaseOrder" >
				  		<form:label path="purchaseOrder">
				  			PO No 
				 		</form:label>  	
				  		<form:select id="purchaseOrderId" path="purchaseOrder.purchaseOrderId" class="purchaseOrderId">
				 			<form:option value=""></form:option>
				 			<form:options items="${purchaseOrderList}" itemValue="purchaseOrderId" itemLabel="purchaseOrderCode" />				 			
				 		</form:select>
				  		<form:errors path="purchaseOrder"  cssClass="errorSimple" /> 
						</aims:column>	
						</c:when>
						
						<c:when test="${deliveryOrder.deliveryOrderId!=null}">
						<p class="span-11">
						<label>
				  			PO No 
				 		</label>
				 		<c:out value="${deliveryOrder.purchaseOrder.purchaseOrderCode}" />
				 		</p> 
						</c:when>
						</c:choose>
						
						
						<p class="span-11">
						<label>
				  			Vendor No		  			
				 		</label>
				 		<c:out value="${deliveryOrder.purchaseOrder.vendor.vendorId}" />
				 		</p>
										
						
						
					<p class="span-11">
						<label>
				  			Vendor Name
				 		</label>
						<c:out value="${deliveryOrder.purchaseOrder.vendor.vendorName}" />
						</p>	
						
					<p class="span-11">
						<label>Address</label>
						<c:out value="${deliveryOrder.purchaseOrder.vendor.contactInfo.contactAddress}"/>
						</p>
						
						
						<p class="span-11">
						<label>Contact No</label>
						<c:out value="${deliveryOrder.purchaseOrder.vendor.contactInfo.contactNo}"/>
						</p>
						
						<aims:column cssErrorClass="error" path="location" >
				  		<form:label path="location">
				  			Receiving Location
				 		</form:label>
				  		<form:select id="locationId" path="location.locationId" class="locationId">
				 			<form:options items="${globalLocation}" itemValue="locationId" itemLabel="locationName" />
				 		</form:select>
				 		<form:errors path="location"  cssClass="errorSimple" /> 
						</aims:column>
						
						
			</div>	
				
			<div class="span-11">
				
						<aims:column cssErrorClass="error" path="deliveryOrderDate" >
				  		<form:label path="deliveryOrderDate">
				  			DO Date  * 
				 		</form:label>
				  		<form:input path="deliveryOrderDate" id="doDate" onkeypress="return restrictCharacters(this, event, validChars);"/> 
				  		<input id="doDate_button" type="button" class="calendarBtn" />
				  		<form:errors path="deliveryOrderDate"  cssClass="errorSimple" /> 
						</aims:column>
						
						
						<p class="span-11">
						<label> Asset Type</label>
						<c:out value="${deliveryOrder.purchaseOrder.assetType}"/>
	  					</p>
	  					
	  					
	  					<p class="span-11">
						<label> From Location</label>
						<c:out value="${deliveryOrder.purchaseOrder.location.locationName}"/>
	  					</p>
	  					
	  				
	  					
	  					<p class="span-11">
						<label> PO Date</label>
						<c:out value="${deliveryOrder.purchaseOrder.purchaseOrderDateToDisplay}"/>
	  					</p>
	  					
	  					
	  					<p class="span-11">
						<label> PO Type</label>
						<c:out value="${deliveryOrder.purchaseOrder.purchaseOrderType}"/>
	  					</p>
	  					
	  					<p class="span-11">
						<label>Access Dept</label>
						<c:choose>
	  					<c:when test="${deliveryOrder.purchaseOrder.accessDepartment.departmentName!=null}">
	  					<c:out value="${deliveryOrder.purchaseOrder.accessDepartment.departmentName}"/>
	  					</c:when>
	  					<c:otherwise>
	  					-
	  					</c:otherwise>
	  					</c:choose>
	  					</p>
	  					
	  					<p class="span-11">
						<label> Company Code</label>
						<c:out value="${deliveryOrder.purchaseOrder.companyCode}"/>
	  					</p>  
	  						  					
			</div>
						
			</fieldset>
			<fieldset>
				<div> <br> </div>
					<input type="button" id="file-uploader" value="Import" class="button positiveDark right"/>
					<input type="button" class="button positiveDark right" value = "Template" onclick="window.open('<c:url value="/resources/sample/deliveryOrder.xls"></c:url>')"/>
				<div> <br> </div>
				
					  		 
				<table id="info" class="gridSearch">
				
				<caption id="header" class="captionLeft">Total number of items : 
		  		<span id="totalItems"></span></caption>
					<thead>
						<tr>
						<c:choose>
						<c:when test="${deliveryOrder.deliveryOrderId==null}">
							<th width="4%">Confirm</th>
						</c:when>
						<c:otherwise>
							<th width="4%">S/N</th>
						</c:otherwise>					
						</c:choose>
		 				    <th width="30%">Asset Model</th>
		 					<th width="30%">Receiving Serial No.</th>
		 					<c:if test="${deliveryOrder.deliveryOrderId!=null}">
		 					<th width="26%">Asset Tag</th>
		 					</c:if>
		 					<c:if test="${deliveryOrder.deliveryOrderId==null}">
		 					<th width="26%">Remarks</th>
		 					</c:if>
		 					<th width="10%">Status</th>
		 					
		 						  						
						</tr>
					</thead>
					<tbody>
					
					<c:choose>
	  				<c:when test="${deliveryOrder.deliveryOrderId==null}">
	  					<input name="delivOrderSubmitted" id="delivOrderSubmitted" type="hidden" value="N"/>
						<c:choose>
							<c:when test="${not empty deliveryOrder.deliveryOrderEquipments}">
							<input name="countEquip" id="countEquip" type="hidden" value="1"/>		
								<c:forEach items="${deliveryOrder.deliveryOrderEquipments}" var="item" varStatus="status">
								
								<input name="deliveryOrderEquipments[${status.index}].deliveryOrderEquipmentId" type="hidden" value="${item.deliveryOrderEquipmentId}"/>
								<input name="deliveryOrderEquipments[${status.index}].deliveryOrder.deliveryOrderId" type="hidden" value="${item.deliveryOrder.deliveryOrderId}"/>
								<input name="deliveryOrderEquipments[${status.index}].assetModel.assetModelId" type="hidden" value="${item.assetModel.assetModelId}"/>
								<input name="deliveryOrderEquipments[${status.index}].assetModel.assetModelCode" type="hidden" value="${item.assetModel.assetModelCode}"/>
								<input name="deliveryOrderEquipments[${status.index}].assetModel.assetModelName" type="hidden" value="${item.assetModel.assetModelName}"/>
																
								<input name="deliveryOrderEquipments[${status.index}].receivedSerialNo" type="hidden" value="${item.receivedSerialNo}"/>
								
									<tr <c:if test="${(status.count%2)==0 }"> class="alt"</c:if>>	
										
										
										<td>
										<input align="center" type="checkbox" class="active" name="deliveryOrderEquipments[${status.index}].active" value="true"
										<c:if test="${item.active}">checked</c:if>/>
	  									</td>
	  									
										
										<td>${item.assetModel.assetModelCode}-${item.assetModel.assetModelName}</td>
										
																
										<td>${item.receivedSerialNo}</td>
										<c:if test="${deliveryOrder.deliveryOrderId!=null}">
										<td>${item.assetTag}</td>
										</c:if>
										<c:if test="${deliveryOrder.deliveryOrderId==null}">
			  							<td></td>	
			  							</c:if>						
											
											<td>
						  						<select name="deliveryOrderEquipments[${status.index}].status" class="status">
						  															  		
											  		<c:forEach items="${statusMap}" var="statusMap">
												        <option value="${statusMap.key}" <c:if test="${item.status==statusMap.key}">selected</c:if>>
												        ${statusMap.value}
												        </option>
												    </c:forEach>
											  	
											  	</select>
											</td>
										
									</tr>
								</c:forEach>
							</c:when>
							<c:otherwise>
							<input name="countEquip" id="countEquip" type="hidden" value="0"/>		
							</c:otherwise>
						</c:choose>
						
						</c:when>
						
						<c:otherwise>
						<input name="delivOrderSubmitted" id="delivOrderSubmitted" type="hidden" value="Y"/>
						<c:choose>
							<c:when test="${not empty deliveryOrder.deliveryOrderEquipments}">
							<input name="countEquip" id="countEquip" type="hidden" value="1"/>		
								<c:forEach items="${deliveryOrder.deliveryOrderEquipments}" var="item" varStatus="status">
								<tr <c:if test="${(status.count%2)==0 }"> class="alt"</c:if>>	
										
										
										<td align="center">${status.index+1}</td>
	  									
										
										<td>${item.assetModel.assetModelCode}-${item.assetModel.assetModelName}</td>
										
																
										<td>${item.receivedSerialNo}</td>
										<c:if test="${deliveryOrder.deliveryOrderId!=null}">
										<td>${item.assetTag}</td>
										</c:if>
										<c:if test="${deliveryOrder.deliveryOrderId==null}">
			  							<td></td>	
			  							</c:if>						
										<td>
						  						<select name="deliveryOrderEquipments[${status.index}].status">
						  															  		
											  		<c:forEach items="${statusMap}" var="statusMap">
												        <option value="${statusMap.key}" <c:if test="${item.status==statusMap.key}">selected</c:if>>
												        ${statusMap.value}
												        </option>
												    </c:forEach>
											  	
											  	</select>
											</td>
										
									</tr>
								</c:forEach>
								
								
							</c:when>
							<c:otherwise>
							<input name="countEquip" id="countEquip" type="hidden" value="0"/>		
							</c:otherwise>
						</c:choose>
						
						</c:otherwise>
						</c:choose>
			
					</tbody>
				</table>
					
					<p class="simple">
					<input type="checkbox" id="checkAll" name="checkAll"/>
					<label for="checkAll">select/deselect all</label>
					</p>
				
						
		</fieldset>
		
			
      <div class="action">
	  	<c:choose>
	  		<c:when test="${deliveryOrder.deliveryOrderId==null}">
	  			<button type="button" class="button positive" onclick="formSubmit()">
	  			Confirm
	  			</button>
	  			<a href="<c:url value="/deliveryOrder/create" />" class="button positive">Cancel</a>
	  			<button type="button" class="button positive" onclick="location.href='<c:url value="/deliveryOrder/search" />'">Back</button>
	  		</c:when>
	  		<c:when test="${deliveryOrder.deliveryOrderId!=null}">
	  			<a href="<c:url value="/deliveryOrder/print/${deliveryOrder.deliveryOrderId}" />" target="_blank" class="button">Print</a>
  				<button type="button" class="button positive" onclick="location.href='<c:url value="/deliveryOrder/search" />'">Back</button>
	  		</c:when>
	  	</c:choose>
	 </div>	
	
	<table id="tmpTable" style="visibility:hidden">
		<tr class="new">
		
		<input name="deliveryOrderEquipments.deliveryOrderEquipmentId" type="hidden" />
		<input name="deliveryOrderEquipments.deliveryOrder.deliveryOrderId" type="hidden" value="${deliveryOrder.deliveryOrderId}"/>
		<input name="deliveryOrderEquipments.assetModel.assetModelId" type="hidden" />
		<input name="deliveryOrderEquipments.assetModel.assetModelCode" type="hidden" />
		<input name="deliveryOrderEquipments.receivedSerialNo" type="hidden" />
		
		<input name="remarks" type="hidden" />
		<input name="deliveryOrderEquipments.assetModel.assetModelName" type="hidden" />
		
		
												
		<!--
		<td>	  	
	  	<span class="indexSNo"></span>	  	
	  	</td>
	  	-->
	  	
	  	<td align="center">
		<input type="checkbox" name="deliveryOrderEquipments.active" class="active"/>
		</td>				
	  	
	  	<td>	
	  	<span class="assetModelName"></span>
	  	</td>
	  	  				
		<td>	  	
	  	<span class="receivedSerialNo"></span>
	  	</td> 
	  	
	  	
	  	<td>	
	  	<span style="color:red;" class="remarks"></span>
	  	</td>
	  	
	  	<td>
			<select name="deliveryOrderEquipments.status" class="status">
												  		
  		<c:forEach items="${statusMap}" var="statusMap">
	        <option value="${statusMap.key}">
	        ${statusMap.value}
	        </option>
	    </c:forEach>
  	
  	</select>
	</td>  		  	
		</tr>
	</table> 
	 
	
	</form:form>
	
	
	
	<script type="text/javascript" src="<spring:url value="/resources/js/select-option-disabled-emulation.js" />"></script>
	<script type="text/javascript" src="<spring:url value="/resources/js/restrictCharactersForDateInput.js" />"></script>
	
	<script type="text/javascript">
	
		var countRows = 0;	
		var validChars = /[1234567890-]/g; 
		
		$(document).ready(function() {
			cal = Calendar.setup({
		          onSelect: function(cal) { cal.hide() },
		          showTime: false
		      });
			rebuiltCalendar();
			$("#purchaseOrderId option[value='']").attr("disabled",true);
			
			var count = $('#info tbody tr').size();
			var delivOrderSubmitted = $('#delivOrderSubmitted').val();
			if(count<=0 || delivOrderSubmitted == 'Y'){
				$('#checkAll').hide();
				$("label[for='checkAll']").hide();
				$('#header').hide();		
			}
			
			else{
				$('#header').show();
				$('#totalItems').text(count);				
			}
			
			$("input[name='checkAll']").click(function() {
		        var checked = $(this).attr("checked");
		       $("#info tr td input:checkbox").attr("checked", checked);
	});
			
			
		});
		
		
		$('.purchaseOrderId').change(function(){
				var purchaseOrderId =  $('#purchaseOrderId').val();
				var url = "<c:url value="/deliveryOrder/creates"/>";
				var form = $('#form');				
				redirect(form,url);
				
		});
		
		function redirect(form,url){
			form.attr('action',url );
			form.submit();
		}
		
		function formSubmit(){
			if(validateForm()){
				var url = "<c:url value="/deliveryOrder/create"/>";
				var form = $('#form');				
				redirect(form,url);
			}
		}
		
		function validateForm(){
			
			var res = true;
			var purchaseOrderId =  $('#purchaseOrderId').val();
			var deliveryOrderCode =  $('#deliveryOrderCode').val();
			var doDate =  $('#doDate').val();
			if(purchaseOrderId == '')
				{	
				    alert(" Pls do select Purchase Order to start processing Delivery Order");
					res = false;
					return res;
				}
			
			else if(deliveryOrderCode == '')
			{	
			    alert(" Pls do enter DO No");
				res = false;
				return res;
			}
			
			else if(doDate == '')
			{	
			    alert(" Pls do enter DO Date");
				res = false;
				return res;
			}
			
			var countEquip = $('#countEquip').val();
			if(countRows<=0 && countEquip == '0')
			{		 alert(" No valid record in imported file to start processing Delivery Order");
					res = false;
					return res;
				
			}
			
			var checkedItem = 0;
			var uncheckedItem = 0;
			
			$(".active").each( function () {				
			       if(this.checked == true)
			    	   checkedItem++;			     
			       else
			    	   uncheckedItem++; 
			});
			
			if(checkedItem==0)
			{					
				alert(" No record is checked to start processing Delivery Order");
				res = false;
				return res;
				
			}
			// Balancing with the left hand side - active checkbox ( tmpTable)
			uncheckedItem--;
			if(uncheckedItem>0) {
				if(confirm('There are '+uncheckedItem+' item(s) not received, please click OK to proceed'))
				{
					res = true;
				}
				
				else
				{
					res = false;
					return res;
				}
			} 		
			
			
			return res;
		}
		
		function rebuiltCalendar()
		{
			cal.manageFields("doDate_button", "doDate", globalJsCalDateFormat);
			  
		}
		
	
		function addRow(indexSNo,assetModelId,assetModelCode,assetModelName,receivedSerialNo,deleted)
		{
			var row = $('#tmpTable tr').clone();
			var rowSize = $('#info tbody tr').size();
			if(!deleted){
				$('input[name=deliveryOrderEquipments.deliveryOrderEquipmentId]',row).attr('name','deliveryOrderEquipments['+countRows+'].deliveryOrderEquipmentId');			
				$('input[name=deliveryOrderEquipments.deliveryOrder.deliveryOrderId]',row).attr('name','deliveryOrderEquipments['+countRows+'].deliveryOrder.deliveryOrderId');
				$('input[name=deliveryOrderEquipments.assetModel.assetModelId]',row).attr('name','deliveryOrderEquipments['+countRows+'].assetModel.assetModelId').val(assetModelId);
				$('input[name=deliveryOrderEquipments.assetModel.assetModelCode]',row).attr('name','deliveryOrderEquipments['+countRows+'].assetModel.assetModelCode').val(assetModelCode);
				$('input[name=deliveryOrderEquipments.assetModel.assetModelName]',row).attr('name','deliveryOrderEquipments['+countRows+'].assetModel.assetModelName').val(assetModelName);
				
				$('input[name=deliveryOrderEquipments.receivedSerialNo]',row).attr('name','deliveryOrderEquipments['+countRows+'].receivedSerialNo').val(receivedSerialNo);
				$('input[name=deliveryOrderEquipments.active]',row).attr('name','deliveryOrderEquipments['+countRows+'].active');
				$('.remarks',row).text("");
				$('.assetModelName',row).text(assetModelCode+"-"+assetModelName);
				$('.active',row).attr('checked', true);
				$('select[name=deliveryOrderEquipments.status]',row).attr('name','deliveryOrderEquipments['+countRows+'].status');
				
				countRows++;
			}
			else{		
				$('.remarks',row).text("Duplicate or Invalid Record. This record wont be inserted. Refer PO Details");
				$('.active',row).attr('checked', false);
				$('.active',row).attr('disabled', true);
				$('.status',row).attr('disabled', true);
				$('.assetModelName',row).text(assetModelCode);
			}
			
			
			$('.receivedSerialNo',row).text(receivedSerialNo);
			//$('.indexSNo',row).text(indexSNo);
			
			row.appendTo('#info tbody');
		}
		
		
		
		new AjaxUpload('file-uploader', {
			  action: '<c:url value="/deliveryOrder/importFileForRepair/${deliveryOrder.purchaseOrder.purchaseOrderId}" />',
			  // File upload name
			  name: 'excelFile',
			  // Submit file after selection
			  autoSubmit: true,
			  responseType: 'json',
			  onSubmit: function(file, extension) {
				  if (! (/^(xls)$/i.test(extension))){
			            // extension is not allowed
			            alert('Error: only .xls allowed');
			            // cancel upload
			            return false;
			       }
				  document.body.style.cursor = 'wait';
				  $('#file-uploader').attr('disabled', true);
				  
			  },
			  onComplete: function(file, responseJSON) {
				  
				  this.enable();
				  countRows = 0;
				  $('#info tbody tr').remove();
				  document.body.style.cursor = 'pointer';
			  	  $('#file-uploader').removeAttr('disabled');
				  if(responseJSON.result!='')
			    	{
					  checkPODropDown();
			    		for(i=0;i<responseJSON.result.length;i++)
			    		{		    			
			    			//alert(responseJSON.result[i].assetModel.assetModelCode);
			    			var indexSNo = i+1;
			    			var assetModelCode = responseJSON.result[i].assetModel.assetModelCode;
			    			var assetModelName = responseJSON.result[i].assetModel.assetModelName!=null?responseJSON.result[i].assetModel.assetModelName:"";
			    			var assetModelId = responseJSON.result[i].assetModel.assetModelId!=null? responseJSON.result[i].assetModel.assetModelId:"-1";
			    			var receivedSerialNo = responseJSON.result[i].receivedSerialNo;
			    			var deleted = responseJSON.result[i].deleted;
			    			addRow(indexSNo,assetModelId,assetModelCode,assetModelName,receivedSerialNo,deleted);		    			
			    		}
			    		
			    		if(responseJSON.result.length>0)
			    			{
			    				$('#checkAll').show();
			    				$("label[for='checkAll']").show();
			    				$('#totalItems').text(responseJSON.result.length);
								$('#header').show();
			    			}
			    	}
				  
				  else
				  {
				  alert('No Record found in the imported file');
				  }
			  
			  
			  if(responseJSON.format!=null && responseJSON.format=='error')
				{
				  alert('Pls do check the format you are trying to import');
				}
			  }
			});
		
		function checkPODropDown(){
			
						$("#purchaseOrderId option").not(":selected").attr("disabled",true);
						emulate(document.getElementById('purchaseOrderId'));
		}			
	</script>
